package com.gensdai.leliang.wxapi;

/**
 * Created by Administrator on 2017/7/13.
 */

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;


import com.gensdai.leliang.activity.NewUser;
import com.gensdai.leliang.activity.Set_social;
import com.gensdai.leliang.activity.user_enter;
import com.gensdai.leliang.base.BaseActivityNoAbs;
import com.gensdai.leliang.entity.User;
import com.gensdai.leliang.entity.UserNameBean;
import com.gensdai.leliang.json_base.json_base;
import com.gensdai.leliang.remoteInterface.ApiService;
import com.gensdai.leliang.serve.ActionEnter;
import com.gensdai.leliang.utils.BaseUtils;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.trello.rxlifecycle2.android.ActivityEvent;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.LogManager;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 微信客户端回调activity示例
 */
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    private static final String TAG = "WXEntryActivity";
    // IWXAPI 是第三方app和微信通信的openapi接口
    private IWXAPI api;

    private BaseResp resp = null;
    private String WX_APP_ID = "wx701d441207f210af";
    // 获取第一步的code后，请求以下链接获取access_token
    private String GetCodeRequest = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
    // 获取用户个人信息
    private String GetUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
    private String WX_APP_SECRET = "f75d2d014df332248acaa683bc0a8e43";

    String unionid;
    String nickname;
    String headimgurl;
    UserNameBean user;
    SharedPreferences share;
    SharedPreferences.Editor ed;
    private final int ENTER = 1;// 登录标识
    private final int BANGIND = 2;// 绑定标识
    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case ENTER:
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {

                            user = (UserNameBean) new json_base().jsonEnter(new JSONObject((String) msg.obj));
                            ActionEnter.saveInfo(user);

                            ed.putString("WXopenid", unionid);  //微信标识

                            ed.commit();
                            WXEntryActivity.this.finish();
                        }
//                        else if (new JSONObject((String) msg.obj)
//                                .getString("message").equals("")) {
                        else {
                            Intent intent = new Intent(WXEntryActivity.this, NewUser.class);
                            intent.putExtra("type", "亲爱的微信用户：" + nickname);
                            intent.putExtra("url", headimgurl);
                            intent.putExtra("WXopenid", unionid);
                            WXEntryActivity.this.startActivity(intent);
                            WXEntryActivity.this.finish();
                        }
                        Toast.makeText(
                                WXEntryActivity.this,
                                new JSONObject((String) msg.obj)
                                        .getString("message"),
                                Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case BANGIND:
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {
                            startActivity(new Intent(WXEntryActivity.this, Set_social.class));
                        } else {

                        }
                        Toast.makeText(
                                WXEntryActivity.this,
                                new JSONObject((String) msg.obj)
                                        .getString("message"),
                                Toast.LENGTH_SHORT).show();

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    WXEntryActivity.this.finish();
                    break;
                default:
                    break;
            }
            WXEntryActivity.this.finish();
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        api = WXAPIFactory.createWXAPI(this, "wx701d441207f210af", false);
        api.handleIntent(getIntent(), this);
        share = getSharedPreferences("User", MODE_PRIVATE);
        ed = share.edit();
        super.onCreate(savedInstanceState);
    }

    // 微信发送请求到第三方应用时，会回调到该方法
    @Override
    public void onReq(BaseReq req) {
        finish();
    }

    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    @Override
    public void onResp(BaseResp resp) {
//        LogManager.show(TAG, "resp.errCode:" + resp.errCode + ",resp.errStr:"
//                + resp.errStr, 1);
        Log.e("resp", resp.toString());
        if (resp.getType() == ConstantsAPI.COMMAND_SENDAUTH) {
            //登录
            switch (resp.errCode) {
                case BaseResp.ErrCode.ERR_OK:
                    //登录成功
                    Log.e(TAG, "登录成功");
                    String code = ((SendAuth.Resp) resp).code;

            /*
             * 将你前面得到的AppID、AppSecret、code，拼接成URL 获取access_token等等的信息(微信)
             */
                    String get_access_token = getCodeRequest(code);
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(get_access_token)
                            .build();
                    Call call = client.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String str = response.body().string();
                            Log.i("wangshu", str);
                            try {
                                JSONObject obj = new JSONObject(str);

                                if (!str.equals("")) {
                                    String access_token = obj
                                            .getString("access_token");
                                    String openid = obj.getString("openid");
                                    String get_user_info_url = getUserInfo(
                                            access_token, openid);
                                    getUserInfo(get_user_info_url);
                                }

                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }

                    });
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL:
                    Log.e(TAG, "登录取消");
                    if (share.getBoolean("enter_state", false)) {
                        startActivity(new Intent(this, Set_social.class));
                    }
                    WXEntryActivity.this.finish();
                    //登录取消
                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED:
                    Log.e(TAG, "登录拒绝");
                    WXEntryActivity.this.finish();
                    //登录拒绝
                    break;
            }
        } else if (resp.getType() == ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX) {
            //分享
            switch (resp.errCode) {
                case BaseResp.ErrCode.ERR_OK:
                    //分享成功
                    Log.e(TAG, "分享成功");

                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL:
                    Log.e(TAG, "分享取消");

                    //分享取消
                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED:
                    Log.e(TAG, "分享拒绝");
                    //分享拒绝
                    break;
            }
            WXEntryActivity.this.finish();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        handleIntent(intent);
    }

    private void handleIntent(Intent intent) {
        SendAuth.Resp resp = new SendAuth.Resp(intent.getExtras());
        if (resp.errCode == BaseResp.ErrCode.ERR_OK) {

        }
    }

    /**
     * 通过拼接的用户信息url获取用户信息
     *
     * @param user_info_url
     */
    private void getUserInfo(String user_info_url) {

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(user_info_url)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                Log.i("wangshu", str);
                try {
                    JSONObject obj = new JSONObject(str);

                    System.out.println("获取用户信息:" + response);

                    if (!response.equals("")) {
                        unionid = obj.getString("unionid");
                        nickname = obj.getString("nickname");
                        headimgurl = obj.getString("headimgurl");
                        Log.e("response:", "unionid:" + unionid + "---nickname:" + nickname + "----headimgurl:" + headimgurl);
                        if (share.getBoolean("enter_state", false)) {
                            Map<String, String> loginParams = new HashMap<>();
                            loginParams.put("unionId", unionid);   //微信标识
                            loginParams.put("userId", share.getString("user_id", ""));
                            Log.e("WX标识：", unionid);
                            bangdingtoStr(loginParams);
                        } else {
                            LoginRequest2Str();
                        }
                    }

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        });
    }


//    @Override
//    protected void onNewIntent(Intent intent) {
//        super.onNewIntent(intent);
//        setIntent(intent);
//        api.handleIntent(intent, this);
//        finish();
//    }

    /**
     * 获取access_token的URL（微信）
     *
     * @param code 授权时，微信回调给的
     * @return URL
     */
    private String getCodeRequest(String code) {
        String result = null;
        GetCodeRequest = GetCodeRequest.replace("APPID",
                urlEnodeUTF8(WX_APP_ID));
        GetCodeRequest = GetCodeRequest.replace("SECRET",
                urlEnodeUTF8(WX_APP_SECRET));
        GetCodeRequest = GetCodeRequest.replace("CODE", urlEnodeUTF8(code));
        result = GetCodeRequest;
        return result;
    }

    /**
     * 获取用户个人信息的URL（微信）
     *
     * @param access_token 获取access_token时给的
     * @param openid       获取access_token时给的
     * @return URL
     */
    private String getUserInfo(String access_token, String openid) {
        String result = null;
        GetUserInfo = GetUserInfo.replace("ACCESS_TOKEN",
                urlEnodeUTF8(access_token));
        GetUserInfo = GetUserInfo.replace("OPENID", urlEnodeUTF8(openid));
        result = GetUserInfo;
        return result;
    }

    private String urlEnodeUTF8(String str) {
        String result = str;
        try {
            result = URLEncoder.encode(str, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    //直接绑定 但是用户必须登录
    private void bangdingtoStr(Map<String, String> loginParams) {
        ApiService.getInstance(this).BIND_THIRDPARTY_DIRECTILY(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = BANGIND;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }


    /**
     * 调用登陆接口
     */
    private void LoginRequest2Str() {
        //获取edit的值后请求

        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("unionId", unionid); //微信标识
        Log.e("微信标识：", unionid);
        toStr(loginParams);
    }

    //返回字符串类型
    private void toStr(Map<String, String> loginParams) {
        ApiService.getInstance(this).LoginRequest2Str(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = ENTER;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }

}